<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>故事库 - AI故事生成器</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href='/static/css/1.css'>
    <style>
        .pagination {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
            margin: 30px 0;
            padding: 10px;
        }

        {#按钮样式#}
        .pagination button {
            min-width: 80px;
            padding: 8px 16px;
            border: 1px solid #ddd;
            border-radius: 6px;
            background-color: #fff;
            color: #333;
            font-size: 14px;
            font-family: inherit;
        }

        .pagination button:not(:disabled):hover {
            background-color: #f5f7fa;
            border-color: #b0b7c3;
            color: blue;

        }

        .pagination button:not(:disabled):active {
            transform: translateY(0);
            box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        .pagination button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            background-color: #f9f9f9;
            color: #999;
            border-color: #e0e0e0;
        }

        .pagination span {
            font-size: 15px;
            color: #555;
            padding: 0 5px;
            font-weight: 500;
        }

        .stories-grid {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            padding: 20px 0;
            justify-content: flex-start;
        }

        .story-card {
            
            flex: 0 0 calc(25% - 15px); 
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease;
            background: white;
            min-width: 200px; 
            max-width: 300px;
        }

        .story-card:hover {
            transform: translateY(-5px);
        }

        .story-info {
            padding: 16px;
        }

        .story-info h3 {
            margin: 0 0 8px;
            font-size: 18px;
            color: #333;
        }

        .story-info p {
            margin: 0 0 12px;
            color: #666;
            font-size: 14px;
            line-height: 1.5;
        }

        .story-meta {
            display: flex;
            justify-content: space-between;
            font-size: 12px;
            color: #888;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 9999;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background-color: #fff;
            width: 80%;
            max-width: 800px;
            padding: 24px;
            border-radius: 12px;
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
            max-height: 80vh;
            overflow-y: auto;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;
            padding-bottom: 12px;
            border-bottom: 1px solid #eee;
        }

        .modal-title {
            font-size: 20px;
            font-weight: 600;
            color: #333;
        }

        .close-btn {
            font-size: 24px;
            color: #999;
            cursor: pointer;
            transition: color 0.2s;
        }

        .close-btn:hover {
            color: #333;
        }

        .modal-author {
            font-size: 14px;
            color: #666;
            margin-bottom: 16px;
            line-height: 1.5;
        }

        .modal-content-text {
            font-size: 16px;
            line-height: 1.8;
            color: #333;
            text-indent: 2em;

        }

        h1 {
            text-align: center;
            margin-bottom: 20px;
        }

        .filters {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 12px 16px;
            background-color: #f9fafb;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .filters button {
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            background-color: forestgreen;
            color: white;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .filters button:hover {
            background-color: black;
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .filters button:active {
            transform: translateY(0);
        }

        .filters select {
            padding: 8px 12px;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            background-color: white;
            font-size: 14px;
            color: #374151;
        }

        .filters select:hover {
            border-color: #9ca3af;
        }

        .filters select:focus {
            outline: none;
            border-color: black;

        }

        .filters input[type="text"] {
            flex: 1;
            padding: 8px 12px;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            background-color: white;
            font-size: 14px;
            color: #374151;
            transition: all 0.2s ease;
        }

        .filters input[type="text"]:hover {
            border-color: #adb5bd;
        }

        .filters input[type="text"]:focus {
            outline: none;
            border-color: black;

        }

        .btn {
            cursor: pointer;
            color: #888;
            margin-right: 4px;
            transition: color 0.2s;
        }

        .btn:hover {
            color: white; 
        }

        .btn.liked {
            color: red; 
        }
        .comments-container {
    margin-top: 20px;
    padding: 15px;
    background-color: #f9f9f9;
    border-radius: 8px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

/* 评论输入区域 */
#input {
    width: 100%;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    resize: vertical;
    min-height: 80px;
    font-size: 14px;
    margin-bottom: 10px;
}

#submit {
    padding: 8px 16px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: background-color 0.3s ease;
}

#submit:hover {
    background-color: #45a049;
}

/* 单个评论项 */
.comments-container > div {
    padding: 12px;
    background-color: white;
    border-radius: 4px;
    margin-bottom: 10px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

/* 评论删除按钮 */
.comments-container > div button {
    background-color: #f44336;
    color: white;
    border: none;
    border-radius: 4px;
    padding: 4px 8px;
    cursor: pointer;
    font-size: 12px;
    float: right;
}

.comments-container > div button:hover {
    background-color: #d32f2f;
}
    </style>
    <link rel="stylesheet" href="/static/css/header.css">
    <link rel="stylesheet" href="/static/css/footer.css">
    <script src="/static/js/header.js" defer></script>
</head>
<body>
<!-- 导航栏 -->
{% include 'header.html' %}

<main class="container">
    <h1>故事库</h1>

    <div class="filters">
        <select name="gategory" id="category">
            <option value="all",{% if current_gategory == 'all' or not current_gategory %} selected{% endif %}>所有类型</option>
            {% for cat in all_categories %}
                <option value="{{ cat.id }}" {% if current_category == cat.id|stringformat:"i" %}selected{% endif %}>
                    {{ cat.name }}
                </option>
            {% endfor %}
        </select>
        <select name="sort" id="sort_f">
            <option value="newest" {% if current_sort == 'newest' %}selected{% endif %}>最新优先</option>
            <option value="hottest" {% if current_sort == 'hottest' %}selected{% endif %}>最热优先</option>
            <option value="most_liked" {% if current_sort == 'most_liked' %}selected{% endif %}>评分最高</option>
        </select>
        <input type="text" id="search" placeholder="搜索故事..." value="{{ current_search }}">
    <button id="searchbtn">搜索</button>
    </div>

    <div class="stories-grid" id="storiesgrid">
    <!-- 在故事循环上方加 -->
        {% for story in  page.object_list %}
            <!-- 故事卡片会在这里重复 -->
            <div class="story-card" data-story-id="{{ story.id }}">
                <div class="story-image">
                    <img src="">
                </div>
                <div class="story-info"
                     data-story-title="{{ story.title }}"
                     data-story-author="{{ story.author.nicheng }}"
                     data-story-content="{{ story.content|escapejs }}">
                    <h3>{{ story.title }}</h3>
                    <p class="truncated-content">{{ story.content|truncatechars:100 }}</p>
                    <div class="story-meta">
                        <span>作者: {{ story.author.username }}</span>
                        <span> {% for cate in story.gategory.all %}
                            {{ cate.name }}{% if not forloop.last %}, {% endif %}
                        {% empty %}
                            无
                        {% endfor %}
                        </span>
{#                        <span class="show-all">⭐ {{ story.likes }}-{{ story.read }}</span>#}
                    <span class="like-container">
                        <span class="btn" data-story-id="{{ story.id }}" data-liked="false">⭐</span>
                        <span class="like-count">{{ story.likes }}点赞数</span>&ensp;
                        <span class="read-count">{{ story.read }}阅读量</span>
                    </span>
                    </div>
                </div>
            </div>
        {% endfor %}
        <!-- 更多故事卡片 -->
    </div>

    <div class="pagination">
        <button id="top" {% if not page.has_previous %}disabled{% endif %}>上一页</button>
        <span id="page">第{{ page.number }}页/共{{ page.paginator.num_pages }}页</span>
        <button id="next" {% if not page.has_next %}disabled{% endif %}>下一页</button>
    </div>
   <div class="modal" id="storyModal">
        <div class="modal-content">
            <button class="close-btn" id="closeModal"></button>
            <div class="modal-header">
                <h2 class="modal-title" id="modalTitle"></h2>
                 <input type="hidden" id="currentStoryId">
            </div>
            <div class="modal-author" id="modalAuthor"></div>
            <div class="modal-content-text" id="modalContent"></div>
            <h3>评论区</h3>
         
            <div>
                 <textarea id="input"></textarea>
                <button id="submit">提交</button>
            </div>
            <div class="comments-container" id="commentList">
                {% for comment in comments %}
                    <div>
                        <p><strong> </strong>:comment[1]</p>
                        <span class="comment-time">{{ comment.created_at|date:"Y-m-d H:i:s" }}</span>
                        <button class="delete-comment" data-comment-id="{{ comment.id }}">删除</button>
                    </div>
                {% endfor %}
            </div>
    
        </div>
    </div>
</main>
<!-- 页脚 -->
{% include 'footer.html' %}
    <script>
        document.addEventListener('DOMContentLoaded',function (){
            const prev1 = document.getElementById('top');
            const next1 = document.getElementById('next');
            const page1 = document.getElementById('page');
            const stories = document.querySelector('.stories-grid');
            const storyModal = document.getElementById('storyModal');
            const modalTitle = document.getElementById('modalTitle');
            const modalAuthor = document.getElementById('modalAuthor');
            const modalContent = document.getElementById('modalContent');
            const category1 = document.getElementById('category');
            const sortf = document.getElementById('sort_f');
            const search = document.getElementById('search');
            const searchbtn = document.getElementById('searchbtn');
            const storiesgrid  =document.getElementById('storiesgrid')
            const closeModal = document.getElementById('closeModal');
            const input = document.getElementById('input');
            const submit = document.getElementById('submit');
            const commentList = document.getElementById('commentList');
            const currentStoryIdInput = document.getElementById('currentStoryId');
            let currentPage = parseInt(new URLSearchParams(window.location.search).get('page') || 1);
            let currentCategory = new URLSearchParams(window.location.search).get('category') || 'all';
            let currentSort = new URLSearchParams(window.location.search).get('sort') || 'newest';
            let currentSearch = new URLSearchParams(window.location.search).get('search') || '';
            function bindDeleteCommentEvents() {
                document.querySelectorAll(".delete-comment").forEach(btn => {
                    btn.addEventListener("click", function () {
                        const commentId = this.getAttribute("data-comment-id");
                        const commentItem = this.closest("div");

                        fetch("/store_system/delete_comment/", {
                            method: "POST",
                            headers: {
                                "Content-Type": "application/x-www-form-urlencoded",
                                "X-CSRFToken": getCookie("csrftoken") 
                            },
                            body: `comment_id=${commentId}`
                        })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    commentItem.remove();  
                                    alert("评论删除成功");
                                } else {
                                    alert(data.message);
                                }
                            })
                            .catch(error => {
                                console.error("删除评论失败:", error);
                                alert("删除评论时发生错误");
                            });
                    });
                });
            }
            function getCookie(name) {
                let cookieValue = null;
                if (document.cookie && document.cookie !== '') {
                    const cookies = document.cookie.split(';');
                    for (let i = 0; i < cookies.length; i++) {
                        const cookie = cookies[i].trim();
                        if (cookie.substring(0, name.length + 1) === (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
    }
            function loadPage(targetPage) {
                const params = new URLSearchParams();
                params.append('page', targetPage);
                params.append('category', currentCategory);
                params.append('sort', currentSort);
                if (currentSearch) params.append('search', currentSearch);
                fetch('{{ request.path }}?' + params.toString(), {
                    method: 'GET',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'Accept': 'application/json'
                    }
                })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('请求失败');
                        }
                        return response.json();
                    })
                    .then(data => {
                        storiesgrid.innerHTML = data.stories_html;

                        page1.textContent = `第${data.current_page}页/共${data.total_pages}页`;

                        prev1.disabled = !data.has_previous;
                        next1.disabled = !data.has_next;

                        currentPage = data.current_page;

                        bindStoryClick();
                        bindLikeEvents(); 
                        {#bindReadEvents();  #}
                    })
                    .catch(error => {
                        stories.innerHTML = `<div class="error">${error.message}，请重试</div>`;
                        console.error('加载失败:', error);
                    });
            }

            function bindStoryClick() {
                document.querySelectorAll('.story-info').forEach(storyInfo => {
                    storyInfo.addEventListener('click', function () {
                        const title = this.getAttribute('data-story-title');
                        const author = this.getAttribute('data-story-author');
                        let content = this.getAttribute('data-story-content');
                        const storyCard = this.closest('.story-card'); // 找到父级卡片
                        const storyId = storyCard.getAttribute('data-story-id'); // 获取故事IDza
                        fetch('/store_system/increase_read/', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRFToken': getCookie('csrftoken'),
                                'X-Requested-With': 'XMLHttpRequest'
                            },
                            body: JSON.stringify({story_id: storyId})
                        })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    // 实时更新页面上的阅读量
                                    const readCountElem = storyCard.querySelector('.read-count');
                                    if (readCountElem) {
                                        readCountElem.textContent = `${data.new_read_count}阅读量`;
                                    }
                                }
                            })
                            .catch(error => console.error('阅读量统计失败:', error));
                        content = content.replace(/\\u000A/g, '\n');
                        content = content.replace(/\\u0022/g, '"');
                        content = content.replace(/\\u0027/g, '"');
                        modalTitle.textContent = title;
                        modalAuthor.textContent = '作者: ' + author;
                        modalContent.textContent = content;
                        currentStoryIdInput.value = storyId;
                        storyModal.style.display = 'flex';
                        fetch(`/store_system/get_comments/?store_id=${storyId}`, {
                            headers: {'X-Requested-With': 'XMLHttpRequest'}
                        })
                            .then(response => response.json())
                            .then(data => {
                                commentList.innerHTML = '';
                                if (data.comments.length === 0) {
                                    commentList.innerHTML = '<p>没有评论</p>';
                                } else {
                                    data.comments.forEach(comment => {
                                        const commentItem = document.createElement('div');
                                        commentItem.innerHTML = `
                                                              <p><strong>${comment.user__username}</strong>: ${comment.content}</p>
                                                               <span class="comment-time">${comment.date}</span>
                                                              <button class="delete-comment" data-comment-id="${comment.id}">删除</button>
                                                           `;
                                        commentList.appendChild(commentItem);
                                    });
                                    bindDeleteCommentEvents();
                                }
                            })
                            .catch(error => {
                                console.error('获取评论失败:', error);
                                commentList.innerHTML = '<p>获取评论失败，请重试</p>';
                            });
                    });
                });
            }

            submit.addEventListener('click', function () {
                const comment = input.value.trim();
                const storyId = currentStoryIdInput.value;
                console.log(storyId)
                if (!storyId) {
                    alert('选择故事评论');
                    return;
                }
                if (!comment) {
                    alert(`评论已提交：${comment}`);
                    input.value = '';
                }
                fetch('/store_system/submit_comment/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCookie('csrftoken'),
                    },
                    body: JSON.stringify({
                        store_id: storyId,
                        content: comment
                    })
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            alert('评论提交成功～');
                            input.value = ''; 
                            fetch(`/store_system/get_comments/?store_id=${storyId}`, {
                                headers: {
                                    'X-Requested-With': 'XMLHttpRequest',
                                }
                            })
                                .then(response => response.json())
                                .then(data => {
                                    const commentListDiv = storyModal.querySelector('#commentList');
                                    commentListDiv.innerHTML = '';
                                    if (data.comments.length === 0) {
                                        commentListDiv.innerHTML = '<p>暂无评论</p>';
                                    } else {
                                        data.comments.forEach(comment => {
                                            const commentItem = document.createElement('div');
                                            commentItem.innerHTML = `
                                               <p><strong>${comment.user__username}</strong>: ${comment.content}</p>
                                               <span class="comment-time">${comment.date}</span>
                                               <button class="delete-comment" data-comment-id="${comment.id}">删除</button>
                                            `;
                                            commentListDiv.appendChild(commentItem);
                                        });
                                        bindDeleteCommentEvents();
                                    }
                                })
                                .catch(error => {
                                    console.error('重新加载评论失败:', error);
                                });
                        } else {
                            alert('评论无法提交' + data.message);
                        }
                    })
                    .catch(error => {
                        console.error('评论提交出错：', error);
                        alert('网络异常，请重试～');
                    });
            });

            function bindLikeEvents() {
                document.querySelectorAll('.btn').forEach(btn => {
                    btn.addEventListener('click', function (e) {
                        e.stopPropagation();
                        e.preventDefault();
                        const storyId = this.getAttribute('data-story-id');
                        const likeBtn = this; // 保存当前按钮引用
                        const likeCountElem = this.nextElementSibling; // 点赞数元素

                        fetch('/store_system/toggle_like/', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRFToken': getCookie('csrftoken'),
                                'X-Requested-With': 'XMLHttpRequest'
                            },
                            body: JSON.stringify({story_id: storyId})
                        })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    likeCountElem.textContent = `${data.new_like_count}点赞数`;
                    // 2. 根据后端返回的 is_liked 状态切换按钮样式
                    if (data.is_liked) {
                        likeBtn.classList.add('liked');
                        likeBtn.style.color = 'red'; // 明确设置红色（避免样式失效）
                    } else {
                        likeBtn.classList.remove('liked');
                        likeBtn.style.color = '#888'; // 恢复默认颜色
                    }
                                } else {
                                    alert('点赞失败: ' + (data.message || '未知错误'));
                                }
                            })
                            .catch(error => console.error('点赞请求失败:', error));
                    });
                });
            }
            
          bindDeleteCommentEvents();
            bindLikeEvents();
            bindStoryClick();
                closeModal.addEventListener('click', function () {
                    storyModal.style.display = 'none';
                });
                window.addEventListener('click', function (event) {
                    if (event.target === storyModal) {
                        storyModal.style.display = 'none';
                    }
                });
                prev1.addEventListener('click', function () {
                    if (!this.disabled) {
                        loadPage(currentPage - 1);
                    }
                })
                next1.addEventListener('click', function () {
                    if (!this.disabled) {
                        loadPage(currentPage + 1);
                    }
                })
                category1.addEventListener('change', () => {
                    currentCategory = category1.value;
                    currentPage = 1;
                    loadPage(currentPage);
                });
                sortf.addEventListener('change', () => {
                    currentSort = sortf.value;
                    currentPage = 1;
                    loadPage(currentPage);
                });
                searchbtn.addEventListener('click', () => {
                    currentSearch = search.value;
                    currentPage = 1;
                    loadPage(currentPage);
                });
                search.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter') {
                        searchbtn.click();
                    }
                });
            })

    </script>

</body>
</html>